import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {
  ElMessage
} from 'element-plus'


NProgress.configure({
  showSpinner: false
}) // NProgress Configuration

const whiteList = ['/login','/home'] // no redirect whitelist


router.beforeEach((to, from, next) => {
  // console.log(to, from, 222222)
  // start progress bar
  NProgress.start()

  // set page title
  //   document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = sessionStorage.getItem('token')
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next()
      sessionStorage.clear()
      NProgress.done()
    } else {
      //   // get user info
      if (store.getters.routeList.length) {
        next()
      } else {
        try {
          store.dispatch('GetUserInfo').then(res => {
            console.log(res)
            res.forEach((o) => {
              router.addRoute(o)
            })
            next({
              ...to,
              replace: true
            })
          })
        } catch (error) {
          ElMessage.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    // next()
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})